class Solution {
  public int[] spiralOrder(int[][] matrix) {
    if (matrix == null || matrix.length == 0) {
      return new int[0];
    }
    int l = 0, t = 0, r = matrix[0].length - 1, b = matrix.length - 1, index = 0;
    int[] res = new int[(b + 1) * (r + 1)];
    while (true) {
      for (int i = l; i <= r; i++) {
        res[index++] = matrix[t][i];
      }
      if (++t > b) {
        break;
      }
      for (int i = t; i <= b; i++) {
        res[index++] = matrix[i][r];
      }
      if (l > --r) {
        break;
      }
      for (int i = r; i >= l; i--) {
        res[index++] = matrix[b][i];
      }
      if (t > --b) {
        break;
      }
      for (int i = b; i >= t; i--) {
        res[index++] = matrix[i][l];
      }
      if (++l > r) {
        break;
      }
    }
    return res;
  }
}